import 'package:flutter_test/flutter_test.dart';
import 'package:awak/common/models/content.dart';
import 'package:awak/common/models/topic.dart';
import 'package:awak/common/models/user.dart';
import 'package:awak/common/repository/content_repository.dart';
import 'package:awak/page/community/topic_data_holder.dart';
import 'package:awak/page/community/content_data_holder.dart';

void main() {
  group('Content Release Feature Tests', () {
    late ContentRepository contentRepository;
    late List<Topic> testTopics;
    late List<Content> testContents;

    setUp(() {
      // 重置状态
      TopicDataHolder.setCurrentTopic(null);
      ContentDataHolder.clearCurrentContent();
      ContentDataHolder.allContents.clear();

      contentRepository = ContentRepository();

      // 创建测试主题
      testTopics = [
        Topic(
          id: 1,
          title: 'Philosophy and Deep Thinking',
          label: 'Philosophical Thinking',
          content: 'Explore the depths of philosophical thought',
          coverImage: 'philosophy.jpg',
          numberPeople: 150,
          userId: 1,
        ),
        Topic(
          id: 2,
          title: 'Psychology Learning',
          label: 'Psychological Learning',
          content: 'Understanding human psychology',
          coverImage: 'psychology.jpg',
          numberPeople: 120,
          userId: 1,
        ),
        Topic(
          id: 3,
          title: 'Getting Up Early',
          label: 'Getting Up Early',
          content: 'Tips for early rising',
          coverImage: 'early.jpg',
          numberPeople: 80,
          userId: 1,
        ),
        Topic(
          id: 4,
          title: 'Traveling Adventures',
          label: 'Traveling',
          content: 'Share your travel experiences',
          coverImage: 'travel.jpg',
          numberPeople: 200,
          userId: 1,
        ),
      ];

      // 设置测试主题
      TopicDataHolder.allTopics = testTopics;

      // 创建测试内容
      testContents = [
        Content(
          id: 1,
          picture: 'content1.jpg',
          description: 'Deep thoughts about existence and meaning of life',
          userId: 1,
          topicId: 1,
          publishedAt: DateTime.now().subtract(Duration(hours: 1)),
        ),
        Content(
          id: 2,
          picture: 'content2.jpg',
          description: 'Understanding human behavior patterns',
          userId: 2,
          topicId: 2,
          publishedAt: DateTime.now().subtract(Duration(hours: 2)),
        ),
      ];

      ContentDataHolder.allContents = testContents;
    });

    test('should handle Issue button navigation to content release page', () {
      // 测试Issue按钮的导航逻辑
      
      // 验证初始状态
      expect(TopicDataHolder.allTopics.isNotEmpty, true);
      expect(TopicDataHolder.allTopics.length, 4);
      
      // 验证主题标签可用性
      final availableLabels = TopicDataHolder.allTopics
          .map((topic) => topic.label ?? 'Unknown')
          .toList();
      
      expect(availableLabels.contains('Philosophical Thinking'), true);
      expect(availableLabels.contains('Psychological Learning'), true);
      expect(availableLabels.contains('Getting Up Early'), true);
      expect(availableLabels.contains('Traveling'), true);
    });

    test('should validate content creation data requirements', () {
      // 测试内容创建的数据需求
      
      final contentText = 'This is a test content about philosophical thinking';
      final selectedTopicLabel = 'Philosophical Thinking';
      final selectedImagePath = 'assets/images/test_content.png';
      
      // 根据选择的标签找到对应的主题
      final selectedTopic = TopicDataHolder.allTopics
          .where((topic) => topic.label == selectedTopicLabel)
          .firstOrNull;
      
      expect(selectedTopic, isNotNull);
      expect(selectedTopic?.id, 1);
      expect(selectedTopic?.label, 'Philosophical Thinking');
      
      // 创建内容对象
      final content = Content(
        picture: selectedImagePath,
        description: contentText,
        userId: 1,
        topicId: selectedTopic!.id!,
        publishedAt: DateTime.now(),
      );
      
      // 验证内容数据
      expect(content.description.isNotEmpty, true);
      expect(content.picture.isNotEmpty, true);
      expect(content.userId, greaterThan(0));
      expect(content.topicId, selectedTopic.id);
      expect(content.publishedAt, isNotNull);
    });

    test('should handle topic label selection correctly', () {
      // 测试主题标签选择功能
      
      final availableLabels = TopicDataHolder.allTopics
          .map((topic) => topic.label ?? 'Unknown')
          .toList();
      
      // 验证所有标签都可用
      expect(availableLabels.length, 4);
      
      // 测试选择不同的标签
      for (String label in availableLabels) {
        final selectedTopic = TopicDataHolder.allTopics
            .where((topic) => topic.label == label)
            .firstOrNull;
        
        expect(selectedTopic, isNotNull);
        expect(selectedTopic?.label, label);
        expect(selectedTopic?.id, greaterThan(0));
      }
    });

    test('should handle content release workflow', () {
      // 测试内容发布工作流程
      
      // 1. 准备发布数据
      final contentText = 'Sharing my thoughts on early morning routines';
      final selectedTopicLabel = 'Getting Up Early';
      final selectedImagePath = 'assets/images/early_morning.png';
      
      // 2. 验证输入数据
      expect(contentText.isNotEmpty, true);
      expect(selectedTopicLabel.isNotEmpty, true);
      
      // 3. 查找对应主题
      final selectedTopic = TopicDataHolder.allTopics
          .where((topic) => topic.label == selectedTopicLabel)
          .firstOrNull;
      
      expect(selectedTopic, isNotNull);
      expect(selectedTopic?.id, 3);
      
      // 4. 创建内容
      final content = Content(
        picture: selectedImagePath,
        description: contentText,
        userId: 1,
        topicId: selectedTopic!.id!,
        publishedAt: DateTime.now(),
      );
      
      // 5. 模拟添加到ContentDataHolder
      final initialContentCount = ContentDataHolder.allContents.length;
      ContentDataHolder.allContents.add(content);
      
      // 6. 验证内容已添加
      expect(ContentDataHolder.allContents.length, initialContentCount + 1);
      expect(ContentDataHolder.allContents.last.description, contentText);
      expect(ContentDataHolder.allContents.last.topicId, selectedTopic.id);
    });

    test('should handle default image when no image selected', () {
      // 测试未选择图片时使用默认图片
      
      final contentText = 'Travel story without custom image';
      final selectedTopicLabel = 'Traveling';
      String? selectedImagePath; // 未选择图片
      
      // 使用默认图片
      final contentPicture = selectedImagePath ?? 'assets/images/default_content.png';
      
      expect(contentPicture, 'assets/images/default_content.png');
      
      // 查找主题
      final selectedTopic = TopicDataHolder.allTopics
          .where((topic) => topic.label == selectedTopicLabel)
          .firstOrNull;
      
      expect(selectedTopic, isNotNull);
      
      // 创建内容
      final content = Content(
        picture: contentPicture,
        description: contentText,
        userId: 1,
        topicId: selectedTopic!.id!,
        publishedAt: DateTime.now(),
      );
      
      expect(content.picture, 'assets/images/default_content.png');
    });

    test('should validate input requirements', () {
      // 测试输入验证需求
      
      // 1. 空内容测试
      String emptyContent = '';
      expect(emptyContent.trim().isEmpty, true);
      
      // 2. 有效内容测试
      String validContent = 'This is a valid content description';
      expect(validContent.trim().isEmpty, false);
      
      // 3. 主题选择测试
      String? nullTopicLabel;
      String validTopicLabel = 'Philosophical Thinking';
      
      expect(nullTopicLabel == null, true);
      expect(validTopicLabel.isNotEmpty, true);
      
      // 4. 主题存在性验证
      final validTopic = TopicDataHolder.allTopics
          .where((topic) => topic.label == validTopicLabel)
          .firstOrNull;
      
      expect(validTopic, isNotNull);
      expect(validTopic?.id, isNotNull);
    });

    test('should handle community updates refresh after content release', () {
      // 测试内容发布后Community Updates的刷新
      
      final initialContentCount = ContentDataHolder.allContents.length;
      
      // 模拟发布新内容
      final newContent = Content(
        id: 99,
        picture: 'new_content.jpg',
        description: 'Newly published content for testing',
        userId: 1,
        topicId: 1,
        publishedAt: DateTime.now(),
      );
      
      // 添加到ContentDataHolder（模拟发布成功）
      ContentDataHolder.allContents.add(newContent);
      
      // 验证内容数量增加
      expect(ContentDataHolder.allContents.length, initialContentCount + 1);
      
      // 验证最新内容
      final latestContent = ContentDataHolder.allContents.last;
      expect(latestContent.id, 99);
      expect(latestContent.description, 'Newly published content for testing');
      
      // 验证内容按时间排序（最新的在前）
      final sortedContents = List<Content>.from(ContentDataHolder.allContents)
        ..sort((a, b) => (b.publishedAt ?? DateTime.now()).compareTo(a.publishedAt ?? DateTime.now()));
      
      expect(sortedContents.first.id, 99); // 最新发布的内容应该在最前面
    });

    test('should handle topic-content relationship correctly', () {
      // 测试主题-内容关系的正确性
      
      // 验证每个内容都关联到正确的主题
      for (final content in testContents) {
        final relatedTopic = TopicDataHolder.getTopicById(content.topicId);
        expect(relatedTopic, isNotNull);
        expect(relatedTopic?.id, content.topicId);
      }
      
      // 测试新内容的主题关联
      final newContent = Content(
        picture: 'psychology_content.jpg',
        description: 'Understanding cognitive biases',
        userId: 1,
        topicId: 2, // Psychology topic
        publishedAt: DateTime.now(),
      );
      
      final relatedTopic = TopicDataHolder.getTopicById(newContent.topicId);
      expect(relatedTopic, isNotNull);
      expect(relatedTopic?.label, 'Psychological Learning');
      expect(relatedTopic?.id, 2);
    });

    test('should handle UI component data consistency', () {
      // 测试UI组件数据一致性
      
      // 验证主题标签数据
      final topicLabels = TopicDataHolder.allTopics
          .map((topic) => topic.label ?? 'Unknown')
          .toList();
      
      expect(topicLabels.every((label) => label.isNotEmpty), true);
      
      // 验证内容数据完整性
      for (final content in testContents) {
        expect(content.description.isNotEmpty, true);
        expect(content.picture.isNotEmpty, true);
        expect(content.userId, greaterThan(0));
        expect(content.topicId, greaterThan(0));
        expect(content.publishedAt, isNotNull);
      }
      
      // 验证主题数据完整性
      for (final topic in testTopics) {
        expect(topic.title?.isNotEmpty ?? false, true);
        expect(topic.label?.isNotEmpty ?? false, true);
        expect(topic.id, greaterThan(0));
        expect(topic.userId, greaterThan(0));
      }
    });

    test('should handle navigation return values correctly', () {
      // 测试导航返回值的正确处理
      
      // 模拟成功发布内容的返回值
      bool publishSuccess = true;
      expect(publishSuccess, true);
      
      // 模拟取消发布的返回值
      bool publishCancelled = false;
      expect(publishCancelled, false);
      
      // 验证根据返回值的不同处理逻辑
      if (publishSuccess) {
        // 应该刷新Community Updates
        final shouldRefresh = true;
        expect(shouldRefresh, true);
      } else {
        // 不应该刷新
        final shouldRefresh = false;
        expect(shouldRefresh, false);
      }
    });
  });
}
